const {
  showMsg
} = require("../../../../utils/config")

import {
  reqUserSubscribeByParam,
  reqUserSubscribe
} from "../../../../request/api"

// pages/subscribe/subscribe.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //phone底部距离
    subscribeList: [ {
      type: '设备告警通知',
      templateId: 'V6ClKqtVNNr3cQrAr_9ny3BAzK68JZuVx0WWGeEUkWI'
    }, {
      type: '删除设备通知',
      templateId: 'j5uSpjguaLecTpxC-HiOEpdBm4quc6dZThEe8RHURP0'
    },{
        type: '用户删除家庭通知',
        templateId: 'mF0pUvai5h1u9YLicXpgGuXAE7VYLcR7LijIPCfjI9M'
      },
      {
        type: '邀请加入家庭成功通知',
        templateId: 'OywbeTAtGTvVccZ-L7dfemzZEGJDt4LMjoqvCS0h9K8'
      },
    ],
    folding: false,
    isForbidden: true
  },

  onLoad() {
    this.onGetSubscribeList()
  },
  onShow() {
    if (wx.getStorageSync('openId')) {
      this.setData({
        isForbidden: false
      })
    } else {
      this.setData({
        isForbidden: true
      })
    }
  },
  async onGetSubscribeList() {
    let res = await reqUserSubscribeByParam({
      openIdList: [wx.getStorageSync('openId')]
    })
    if (res.code !== 20000) return showMsg(res.message)
    let {
      list
    } = res.data
    list.forEach((item, index) => {
      for (let i = 0; i < this.data.subscribeList.length; i++) {
        if (item.templateId == this.data.subscribeList[i].templateId) {
          this.data.subscribeList[i].count = item.count
        }
        if (index == list.length - 1 && i == this.data.subscribeList.length - 1) {
          this.setData({
            subscribeList: this.data.subscribeList
          })
          wx.hideLoading()
        }
      }
    })
    wx.hideLoading()
  },
  onGetAuth(templateid, count) {
    console.log(templateid,'templateid');
    let _this = this;
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        if (!res.subscriptionsSetting.mainSwitch) {
          wx.showModal({
            title: '订阅失败',
            content: '您已经取消了订阅，将无法收到订阅消息的推送',
            cancelText: '暂不开启',
            confirmText: '重新开启',
            complete: (res) => {
              if (res.cancel) {
                console.log('取消')
              }
              if (res.confirm) {
                this.onOpenSetting()
              }
            }
          })
        } else {
          wx.requestSubscribeMessage({
            tmplIds: [templateid],
            success: async (result) => {
              console.log(result, "result")
              if (result[templateid] == "accept") {
                wx.showLoading({
                  title: '订阅中',
                  mask: true
                })
                // let res = await reqUserSubscribe({
                //   openId: wx.getStorageSync('openId'),
                //   type: count == 0 ? 1 : 2,
                //   appId: 'wx3322993fa30146ca',
                //   templates: [{
                //     templateId: templateid,
                //     status: 'accept'
                //   }]
                // })
                // if (res.code !== 20000) {
                //   wx.hideLoading()
                //   showMsg(res.message)
                //   return
                // }
                this.data.listTimer && clearTimeout(this.data.listTimer) || ''
                this.setData({
                  listTimer: setTimeout(() => {
                    _this.onGetSubscribeList()
                  }, 1000)
                })
                console.log('订阅成功')
              } else {
                console.log('取消订阅')
                wx.showModal({
                  title: '订阅失败',
                  content: '您已经取消了订阅，将无法收到订阅消息的推送',
                  cancelText: '暂不开启',
                  confirmText: '重新开启',
                  complete: (res) => {
                    if (res.cancel) {
                      console.log('取消')
                    }
                    if (res.confirm) {
                      this.onOpenSetting()
                    }
                  }
                })
              }
            },
            fail(err) {
              console.log(err, "err")
            }
          })
        }
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
  onUnload() {
    this.setData({
      listTimer: null
    })
  },
  // 订阅
  onSubscribe(e) {
    if (this.data.isForbidden) {
      wx.showModal({
        title: '订阅失败',
        content: '请在个人中心页面绑定微信后再进行订阅操作',
        complete: (res) => {
          if (res.cancel) {

          }

          if (res.confirm) {
            wx.switchTab({
              url: '/pages/consumer/user/user',
            })
            // wx.navigateBack()
          }
        }
      })
      return;
    }
    let templateid = e.currentTarget.dataset.templateid
    let count = e.currentTarget.dataset && e.currentTarget.dataset.count || 0
    this.onGetAuth(templateid, count)
  },
  onOpenSetting() {
    wx.openSetting({
      authSetting: true,
      withSubscriptions: true,
      success(res) {
        console.log(res, "重新开启")
      },
      fail(err) {
        console.log(err, "err");
        showMsg('获取授权失败')
      }
    })
  },

  onFolding() {
    this.setData({
      folding: !this.data.folding
    })
  },
})